<template>
  <div class="rebate-detail">
    <div class="container">
      <div class="rebate-detail-title text-overflow">商户代理分润</div>
      <!-- 查询方式 -->
      <el-row  :gutter="10" style="padding:20px 10px;border-bottom:1px solid #efefef;">
        <el-col :span="3">
          <el-input class="filter-input" v-model="filters.phone" placeholder="手机号码查询"></el-input>
        </el-col>
        <el-col :span="3">
          <el-input class="filter-input" v-model="filters.orderCode" placeholder="订单号查询"></el-input>
        </el-col>
        <el-col :span="3">
          <el-select class="filter-select" v-model="filters.tradeStatus" clearable placeholder="状态">
            <el-option
              v-for="item in statusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-select
            class="filter-select"
            v-model="filters.selStatus"
            clearable
            placeholder="选择清算方式"
          >
            <el-option
              v-for="item in sel_status"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-date-picker
            style="width:150px"
            v-model="filters.startDate"
            type="date"
            placeholder="选择开始时间"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-col>
        <el-col :span="3">
          <el-date-picker
             style="width:150px"
            v-model="filters.endDate"
            type="date"
            placeholder="选择截止时间"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-col>
        <el-col style="text-overflow:nowrap" :span="6">
          <el-button @click="queryByFilter(0)">查询</el-button>
          <!-- <el-button @click="()=>{this.dialogVisible = true}">同步数据</el-button> -->
          <el-button @click="clearInfo">手动清零</el-button>
        </el-col>
      </el-row>
      <div class="rebate-detail-list" v-loading="loading">
        <div class="rebate-list">
          <el-table :data="rebate_list" style="width: 100%">
            <el-table-column
              type="index"
              width="50">
            </el-table-column>
            <el-table-column
              v-for="cell in rebate_list_header"
              :key="cell.prop"
              :prop="cell.prop"
              :label="cell.label"
              :formatter="formatterList"
            ></el-table-column>
            <!-- <el-table-column fixed="right" label="操作" width="80">
              <template slot-scope="scope">
                <el-button type="text" size="small">操作</el-button>
              </template>
            </el-table-column> -->
          </el-table>
        </div>
        <div class="pages-control">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page.sync="pages.currentPage+1"
            :page-size="pages.page_size"
            layout="prev, pager, next, jumper"
            :total="pages.total"
          ></el-pagination>
        </div>
        <div>
          <el-button download="我是被导出的表格.xls" @click="downloadTable">下载表格</el-button>
        </div>
      </div>

      <!-- 刷新统计 -->
      <el-dialog title="统计数据" :visible.sync="dialogVisible" width="50%">
        <p>请选择需要刷新的日期！将同步选择日期之前一周的数据！</p>
        <el-date-picker
          style="width:150px"
          v-model="dateString"
          type="date"
          placeholder="选择日期"
          format="yyyy 年 MM 月 dd 日"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateInfo">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import USB from "@/utils/USB.js"; // 获取url
import moment from "moment";
export default {
  name: "rebate-detail",
  data() {
    return {
      dateString: "",
      dialogVisible: false,
      loading: false,
      filters: {
        phone: null,
        orderCode: null,
        selStatus: null,
        startDate: "",
        endDate: "",
        tradeStatus: "" //
      },
      statusList: [
        { value: "WAIT_BUYER_PAY", label: "创建" },
        { value: "TRADE_SUCCESS", label: "成功" },
        { value: "TRADE_FAILURE", label: "失败" },
        { value: "TRADE_FINISHED", label: "完结" },
        { value: "TRADE_CLOSED", label: "关闭" },
        { value: "TRADE_REFUND", label: "转入退款" },
        { value: "TRADE_REVOKED", label: "已撤销" },
        { value: "TRADE_PAYING", label: "用户支付中" }
      ],
      rebate_list: [],
      rebate_list_header: [
        { prop: "orderNo", label: "订单号" },
        { prop: "userName", label: "用户名称" },
        { prop: "orderType", label: "订单类型" },
        { prop: "selStatus", label: "结算状态" },
        { prop: "agentFee", label: "代理商分润" },
        // { prop: "platformFee", label: "平台分润" },
        { prop: "merchantName", label: "商户名称" },
        { prop: "totalAmount", label: "订单金额" },
        { prop: "body", label: "商品信息" },
        { prop: "tradeStatus", label: "订单状态" },
        { prop: "createTime", label: "创建时间" }
      ],
      pages: {
        total: 10,
        page_size: 20,
        currentPage: 0
      },
      sel_status: [{ value: 1, label: "已清算" }, { value: 2, label: "未清算" }]
    };
  },
  components: {},
  created() {
    this.queryByFilter(0);
  },
  mounted() {},
  methods: {
    queryByFilter(page = 0) {
      const userId = sessionStorage.getItem(4);
      let url = `paymentchannel/pay_order/query/lists?userId=${userId}&page=${page}&size=${
        this.pages.page_size
      }`;
      for (let key in this.filters) {
        if (
          this.filters[key] !== null &&
          this.filters[key] !== "" &&
          this.filters[key] !== undefined
        ) {
          url += `&${key}=${this.filters[key]}`;
        }
      }
      this.$Http
        .get(url)
        .then(res => {
          if (
            res.data.resp_code === "000000" &&
            Object.keys(res.data.result).length !== 0
          ) {
            this.rebate_list = res.data.result.page.content;
            this.pages.total = res.data.result.page.totalElements;
          } else {
            this.$message.warning(res.data.resp_message);
          }
        })
        .catch(err => {
          this.$message.error("服务器繁忙！请稍后再试");
        });
    },
    updateInfo() {
      // 同步订单
      let url = `paymentchannel/stats_orders`;
      let params = ``;
      if (this.dateString) {
        params = `date=${this.dateString}`;
      }
      this.$Http
        .post(url, params)
        .then(res => {
          this.$message(res.data.resp_message);
          if (res.data.resp_code === "000000") {
            this.dialogVisible = false;
            this.$alert("同步订单成功，点击继续同步数据！", "同步数据", {
              confirmButtonText: "确定",
              callback: action => {
                this.updateData();
              }
            });
          }
        })
        .catch(err => {
          this.$message.error("同步失败！");
        });
    },
    updateData() {
      // 同步数据
      let url = `paymentchannel/send_pos`;
      this.$Http
        .post(url, "")
        .then(res => {
          this.$message(res.data.resp_message);
          if (res.data.resp_code === "000000") {
            this.$alert("同步数据成功，点击继续补单！", "补单", {
              confirmButtonText: "确定",
              callback: action => {
                this.updateOrder();
              }
            });
          }
        })
        .catch(err => {
          this.$message.error("服务器繁忙！请稍后再试");
        });
    },
    updateOrder() {
      // 手工补单
      let url = `user/payment_profits/retry_to_accounts`;
      this.$Http
        .post(url, "")
        .then(res => {
          this.$message(res.data.resp_message);
        })
        .catch(err => {
          this.$message.error("服务器繁忙！请稍后再试");
        });
    },
    clearInfo() {
      // 清空 paymentchannel/pay_order/update/selStatus  参数 selStatus
      this.$confirm("请确定要清空该信息吗？", "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(_ => {
        this.loading = true;
        let ps = [];
        for (let key in this.filters) {
          if (
            this.filters[key] !== null &&
            this.filters[key] !== "" &&
            this.filters[key] !== undefined
          ) {
            ps.push(`${key}=${this.filters[key]}`);
          }
        }
        let url = `paymentchannel/pay_order/update/selStatus`;
        let params = ps.join("&") + '&userId=' + sessionStorage.getItem(4);
        this.$Http
          .get(url + "?" + params)
          .then(res => {
            this.loading = false;
            if (res.data.resp_code === "000000") {
              this.$message.success(res.data.resp_message);
            } else {
              this.$message.info(res.data.resp_message);
            }
          })
          .catch(err => {
            this.loading = false;
            this.$message.error("服务器繁忙！请稍后再试");
          });
      });
    },
    // filterList(type) {
    //   this.loading = true;
    //   let params =
    //     type && this.filters[type]
    //       ? `page=0&size=${this.pages.page_size}&phone=${this.filters[type]}`
    //       : `page=0&size=${this.pages.page_size}`;
    //   this.$Http
    //     .post(USB.U90, params)
    //     .then(res => {
    //       this.loading = false;
    //       if (res.data.resp_code === "000000") {
    //         this.pages.total = res.data.result.totalElements;
    //         this.rebate_list = res.data.result.content;
    //       } else {
    //         this.$notify.info({
    //           title: "提示",
    //           message: res.data.resp_message
    //         });
    //       }
    //     })
    //     .catch(err => {
    //       this.$notify.error({
    //         title: "错误",
    //         message: "获取分润信息失败！"
    //       });
    //     });
    // },
    handleCurrentChange(value) {
      this.queryByFilter(value-1);
    },
    formatterList(row, column, cellValue, index) {
      //  格式化信息
      if (column.label === "创建时间") {
        return moment(cellValue).format("YYYY-MM-DD HH:mm:ss");
      }else if(column.label === "结算状态"){
        return cellValue==1?'已清算':'未清算'
      } else {
        return cellValue===null?'--':cellValue;
      }
    },
    downloadTable() {}
  }
};
</script>
<style scoped>
.rebate-detail {
  box-sizing: border-box;
  padding: 20px;
}
.rebate-detail-title {
  height: 50px;
  line-height: 50px;
  font-size: 26px;
  color: #409eff;
  padding: 5px 20px;
  border-bottom: 1px solid #ededed;
}
.container {
  border: 1px solid #ededed;
}
.filter-box {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 15px;
  flex-wrap: nowrap;
  overflow: hidden;
}
.filter-cell {
  width: 200px;
}
.rebate-list {
  min-height: 300px;
  position: relative;
  border-top: 1px solid #efefef;
}
.pages-control {
  border-top: 1px solid #ededed;
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.no-data {
  min-height: 300px;
  text-align: center;
  line-height: 200px;
}

table {
  background-color: #fff;
  width: 100%;
  font-size: 12px;
  min-width: 900px;
}
th {
  position: relative;
  word-wrap: normal;
  text-overflow: ellipsis;
  vertical-align: middle;
  border-bottom: 1px solid #ebeef5;
}
thead {
  padding: 8px 0;
  color: #909399;
}
tr {
  padding: 8px 0;
}
tr:hover {
  background-color: #f5f7fa;
}
td {
  border: none;
  border-bottom: 1px solid #ebeef5;
}
.table-cell {
  white-space: normal;
  word-break: break-all;
  line-height: 22px;
  padding: 10px 10px;
  text-align: center;
  min-width: 40px;
  box-sizing: border-box;
}
.index-cell {
  min-width: 50px;
}
</style>